package com.nikmesoft.android.ebox.activities;

import java.io.File;
import java.io.IOException;
import com.nikmesoft.android.ebox.R;
import com.nikmesoft.android.ebox.helpers.FileHelper;
import com.nikmesoft.android.ebox.models.Item.Type;
import android.media.ExifInterface;
import com.nikmesoft.android.ebox.activities.PhotosActivity;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.util.FloatMath;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnTouchListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.PointF;

public class ViewPhotosActivity extends Activity implements OnTouchListener {
	private String path_image;

	private String name;

	private static final String TAG = "Touch";
	@SuppressWarnings("unused")
	private static final float MIN_ZOOM = 1f, MAX_ZOOM = 1f;
	private File imgFile;
	// These matrices will be used to scale points of the image
	Matrix matrix = new Matrix();
	Matrix savedMatrix = new Matrix();
	ImageView myImage;
	// The 3 states (events) which the user is trying to perform
	static final int NONE = 0;
	static final int DRAG = 1;
	static final int ZOOM = 2;
	int mode = NONE;
	private Bitmap bitmap;
	private String currentPath;
	// these PointF objects are used to record the point(s) the user is touching
	PointF start = new PointF();
	PointF mid = new PointF();
	float oldDist = 1f;
	private ProgressDialog progressDialog;

	@SuppressWarnings("deprecation")
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_view_photos);
		myImage = (ImageView) findViewById(R.id.imageViewName);
		registerForContextMenu(myImage);

		name = getIntent().getStringExtra("KEY");

		myImage.setBackgroundColor(Color.BLACK);
		myImage.setOnTouchListener(this);
		path_image = getIntent().getStringExtra("PATH")
				+ getIntent().getStringExtra("KEY");
		currentPath = getIntent().getStringExtra("Currentpath");
		bitmap = (Bitmap) getLastNonConfigurationInstance();
		progressDialog = new ProgressDialog(this);
		progressDialog.setMessage("Decoding your photo...");
		if (bitmap == null) {
			new DecryptTask().execute();
		} else {
			myImage.setImageBitmap(bitmap);
		}

	}

	private class DecryptTask extends AsyncTask<Void, Void, Bitmap> {

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			progressDialog.show();
		}

		@Override
		protected Bitmap doInBackground(Void... params) {
			// decode
			File sourceLocation = new File(FileHelper.getInstance()
					.getFullPath(path_image, Type.Photo));
			imgFile = new File(FileHelper.getInstance().getFullPath(
					path_image + "e", Type.Photo));

			try {
				FileHelper.getInstance().decode(sourceLocation, imgFile);
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			Bitmap bitmap = null;
			if (imgFile.exists()) {
				int targetW = 1024;
				int targetH = 1024;

				// Get the dimensions of the bitmap
				BitmapFactory.Options bmOptions = new BitmapFactory.Options();
				bmOptions.inJustDecodeBounds = true;
				BitmapFactory.decodeFile(imgFile.getAbsolutePath(), bmOptions);
				int photoW = bmOptions.outWidth;
				int photoH = bmOptions.outHeight;

				// Determine how much to scale down the image
				int scaleFactor = Math.min(photoW / targetW, photoH / targetH);

				// Decode the image file into a Bitmap sized to fill the View
				bmOptions.inJustDecodeBounds = false;
				bmOptions.inSampleSize = scaleFactor;
				bmOptions.inPurgeable = true;

				bitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath(),
						bmOptions);
				ExifInterface exif;
				try {
					exif = new ExifInterface(imgFile.getAbsolutePath());
					int orientation = exif.getAttributeInt(
							ExifInterface.TAG_ORIENTATION, 1);
					Log.e("orientation", "" + orientation);
					Matrix m = new Matrix();

					if ((orientation == 3)) {
						m.postRotate(180);
						Log.e("in orientation", "" + orientation);
						bitmap = Bitmap.createBitmap(bitmap, 0, 0,
								bitmap.getWidth(), bitmap.getHeight(), m, true);
					} else if (orientation == 6) {
						m.postRotate(90);
						Log.e("in orientation", "" + orientation);
						bitmap = Bitmap.createBitmap(bitmap, 0, 0,
								bitmap.getWidth(), bitmap.getHeight(), m, true);
					} else if (orientation == 8) {
						m.postRotate(270);
						Log.e("in orientation", "" + orientation);
						bitmap = Bitmap.createBitmap(bitmap, 0, 0,
								bitmap.getWidth(), bitmap.getHeight(), m, true);
					}
				} catch (IOException e) {
					e.printStackTrace();
				}

			}
			imgFile.delete();
			imgFile = new File(FileHelper.getInstance().getFullPath(path_image,
					Type.Photo));
			return bitmap;
		}

		@Override
		protected void onPostExecute(Bitmap result) {

			if (result != null) {
				myImage.setImageBitmap(result);
				bitmap = result;
			}
			progressDialog.dismiss();
		}

	};

	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menu_photos, menu);
		return true;
	}

	public void confirmDialog() {
		AlertDialog.Builder alert = new AlertDialog.Builder(this);

		alert.setTitle("Delete");
		alert.setMessage("Are you sure ?");

		// Set an EditText view to get user input

		alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				imgFile.delete();
				setResult(RESULT_OK);
				finish();

			}
		});
		alert.setNegativeButton("Cancel",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						// Canceled.
					}
				});

		alert.show();

	}

	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		menu.setHeaderTitle("Task");
		menu.add(0, v.getId(), 0, getString(R.string.contextmenu_item_rename));
		menu.add(1, v.getId(), 0,
				getString(R.string.contextmenu_item_back2galley));
		menu.add(2, v.getId(), 0, getString(R.string.contextmenu_item_delete));
	}

	public boolean onContextItemSelected(MenuItem item) {

		if (item.getTitle().equals(getString(R.string.contextmenu_item_rename))) {
			createRenameDialog(item.getItemId());

		} else if (item.getTitle().equals(
				getString(R.string.contextmenu_item_back2galley))) {
			saveTogallery();
			Toast.makeText(ViewPhotosActivity.this, "Image's saved back...!",
					Toast.LENGTH_SHORT).show();
		} else if (item.getTitle().equals(
				getString(R.string.contextmenu_item_setWallpaper))) {
			setAsWallpaper();
		} else {
			return false;
		}
		return true;
	}

	public void createRenameDialog(int id) {
		AlertDialog.Builder alert = new AlertDialog.Builder(this);

		alert.setTitle("Rename");
		alert.setMessage("Enter new name");

		// Set an EditText view to get user input
		final EditText input = new EditText(this);
		input.setHint(nameToHint());
		alert.setView(input);

		alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {

				String ext;
				String newname = input.getText().toString().trim();
				if (newname.equals("")) {
					Toast.makeText(ViewPhotosActivity.this, "Name is empty",
							Toast.LENGTH_SHORT).show();
				} else {
					File dir = new File(currentPath);
					ext = "."
							+ name.substring((name.lastIndexOf(".") + 1),
									name.length());
					if (ext.equals("." + name)) {
						ext = "";
					}

					if (dir.exists()) {
						File from = new File(dir, name);
						File to = new File(dir, newname + ext);
						if (to.exists()) {
							Toast.makeText(ViewPhotosActivity.this,
									"Name is exist!", Toast.LENGTH_SHORT)
									.show();
						} else {
							from.renameTo(to);
							Toast.makeText(ViewPhotosActivity.this,
									"Rename complete..!", Toast.LENGTH_SHORT)
									.show();
						}
					}
					setResult(RESULT_OK);
					finish();

				}
			}
		});
		alert.setNegativeButton("Cancel",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						// Canceled.
					}
				});

		alert.show();

	}

	public String nameToHint() {
		String test = name;
		String ext;
		ext = "." + name.substring((name.lastIndexOf(".") + 1), name.length());
		return test.substring(0, test.length() - ext.length());
	}

	public void saveTogallery() {
		String file_path = currentPath + name;
		File sourceFile = new File(file_path);
		File desFile = new File(Environment.getExternalStorageDirectory()
				.getAbsolutePath() + "/DCIM/" + name);
		if (!desFile.exists()) {
			try {
				desFile.createNewFile();
				PhotosActivity.copyDirectory(sourceFile, desFile);
				sourceFile.delete();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	@SuppressWarnings("deprecation")
	public void setAsWallpaper() {
		Context context = this.getBaseContext();
		try {
			context.setWallpaper(bitmap);

		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.share_photos:
			Intent shareIntent = new Intent(Intent.ACTION_SEND);
			Uri phototUri = Uri.parse(path_image);
			shareIntent.setData(phototUri);
			shareIntent.setType("image/*");
			shareIntent.putExtra(Intent.EXTRA_STREAM, phototUri);
			startActivity(Intent.createChooser(shareIntent, "Share Via"));
			break;
		case R.id.delete_photos:
			confirmDialog();
			break;
		case R.id.task_photos:
			openContextMenu(myImage);
			break;
		}
		finishActivity(RESULT_OK);
		return true;

	}

	@Override
	public Object onRetainNonConfigurationInstance() {
		return bitmap;
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
	}

	public boolean onTouch(View v, MotionEvent event) {
		ImageView view = (ImageView) v;
		view.setScaleType(ImageView.ScaleType.MATRIX);
		float scale;

		dumpEvent(event);
		// Handle touch events here...

		switch (event.getAction() & MotionEvent.ACTION_MASK) {
		case MotionEvent.ACTION_DOWN: // first finger down only
			savedMatrix.set(matrix);
			start.set(event.getX(), event.getY());
			Log.d(TAG, "mode=DRAG"); // write to LogCat
			mode = DRAG;
			break;

		case MotionEvent.ACTION_UP: // first finger lifted

		case MotionEvent.ACTION_POINTER_UP: // second finger lifted

			mode = NONE;
			Log.d(TAG, "mode=NONE");
			break;

		case MotionEvent.ACTION_POINTER_DOWN: // first and second finger down

			oldDist = spacing(event);
			Log.d(TAG, "oldDist=" + oldDist);
			if (oldDist > 5f) {
				savedMatrix.set(matrix);
				midPoint(mid, event);
				mode = ZOOM;
				Log.d(TAG, "mode=ZOOM");
			}
			break;

		case MotionEvent.ACTION_MOVE:

			if (mode == DRAG) {
				matrix.set(savedMatrix);
				matrix.postTranslate(event.getX() - start.x, event.getY()
						- start.y); // create the transformation in the matrix
									// of points
			} else if (mode == ZOOM) {
				// pinch zooming
				float newDist = spacing(event);
				Log.d(TAG, "newDist=" + newDist);
				if (newDist > 5f) {
					matrix.set(savedMatrix);
					scale = newDist / oldDist; // setting the scaling of the
												// matrix...if scale > 1 means
												// zoom in...if scale < 1 means
												// zoom out
					matrix.postScale(scale, scale, mid.x, mid.y);
				}
			}
			break;
		}

		view.setImageMatrix(matrix); // display the transformation on screen

		return true; // indicate event was handled
	}

	@SuppressLint("FloatMath")
	private float spacing(MotionEvent event) {
		float x = event.getX(0) - event.getX(1);
		float y = event.getY(0) - event.getY(1);
		return FloatMath.sqrt(x * x + y * y);
	}

	private void midPoint(PointF point, MotionEvent event) {
		float x = event.getX(0) + event.getX(1);
		float y = event.getY(0) + event.getY(1);
		point.set(x / 2, y / 2);
	}

	/** Show an event in the LogCat view, for debugging */
	@SuppressWarnings("deprecation")
	private void dumpEvent(MotionEvent event) {
		String names[] = { "DOWN", "UP", "MOVE", "CANCEL", "OUTSIDE",
				"POINTER_DOWN", "POINTER_UP", "7?", "8?", "9?" };
		StringBuilder sb = new StringBuilder();
		int action = event.getAction();
		int actionCode = action & MotionEvent.ACTION_MASK;
		sb.append("event ACTION_").append(names[actionCode]);

		if (actionCode == MotionEvent.ACTION_POINTER_DOWN
				|| actionCode == MotionEvent.ACTION_POINTER_UP) {
			sb.append("(pid ").append(
					action >> MotionEvent.ACTION_POINTER_ID_SHIFT);
			sb.append(")");
		}

		sb.append("[");
		for (int i = 0; i < event.getPointerCount(); i++) {
			sb.append("#").append(i);
			sb.append("(pid ").append(event.getPointerId(i));
			sb.append(")=").append((int) event.getX(i));
			sb.append(",").append((int) event.getY(i));
			if (i + 1 < event.getPointerCount())
				sb.append(";");
		}

		sb.append("]");
		Log.d("Touch Events ---------", sb.toString());
	}
}
